package com.woniu108.order.controller;


import cn.hutool.core.bean.BeanUtil;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu108.carService.commons.log.AdminHistoryLog;
import com.woniu108.carService.commos.model.Result;
import com.woniu108.carService.commos.util.JWTUtil;
import com.woniu108.carService.commos.util.RedisUtil;
import com.woniu108.order.model.dto.OrderProductDto;
import com.woniu108.order.model.form.*;
import com.woniu108.order.model.param.OrderProductCancelParam;
import com.woniu108.order.model.param.OrderProductCreateParam;
import com.woniu108.order.model.param.OrderProductUpdateAddressParam;
import com.woniu108.order.model.param.QueryOrderProductConditionParam;
import com.woniu108.order.service.OrderProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 * 商品订单表 前端控制器
 * </p>
 *
 * @author yanxi
 * @since 2024-05-23
 */
@RestController
@RequestMapping("/orderProduct")
@Api(tags = "商品订单接口")
public class OrderProductController {
    @Resource
    private OrderProductService orderProductService;

    @Resource
    private RedisUtil redisUtil;

    /**
     * token获取用户id
     * @param token 会话跟踪
     * @return 用户id
     */
    public String getUserIdByToken(String token){
        String refreshToken = redisUtil.getString(token);
        return JWTUtil.parseUserToken(refreshToken).get("userId").toString();
    }

    /**
     * 条件查询订单（管理员）
     * @param form 订单查询订单条件
     * @return 分页后的订单列表
     */
    @PostMapping("/queryOrderProductsByCondition.api")
    @ApiOperation("条件查询订单（管理员）")
    public Result queryOrderByConditionToManager(@RequestBody QueryOrderProductConditionForm form){
        QueryOrderProductConditionParam param = BeanUtil.toBean(form, QueryOrderProductConditionParam.class);
        Page<OrderProductDto> orderProductDtos = orderProductService.selectOrderByConditionToManager(param);
        return Result.newPageInstance(OrderProductDto.class).setData(orderProductDtos).setMsg("查询多个订单信息成功");
    }

    /**
     * 条件查询订单（用户）
     * @param form 订单查询订单条件
     * @param token 登录用户token
     * @return 分页后的订单列表
     */
    @PostMapping("/queryOrderProductsByConditionToUser")
    @ApiOperation("条件查询订单（用户）")
    public Result queryOrderByCondition(@RequestBody QueryOrderProductConditionByUserForm form, @RequestHeader String token){
        String userId = getUserIdByToken(token);


        QueryOrderProductConditionParam param = BeanUtil.toBean(form, QueryOrderProductConditionParam.class);
        if(userId!=null) {
            param.setUserId(userId);
        }
        Page<OrderProductDto> orderProductDtos = orderProductService.selectOrderByCondition(param);
        return Result.newPageInstance(OrderProductDto.class).setData(orderProductDtos).setMsg("查询多个订单信息成功");
    }

    /**
     * 据编号查询单个订单
     * @param orderNum 精确订单编号
     * @return 商品订单
     */
    @GetMapping("/queryOrderProductByOrderNum/{orderNum}.c")
    @ApiOperation("据编号查询单个订单")
    public Result<OrderProductDto> queryOrderProductByOrderNum(@PathVariable("orderNum") @ApiParam("订单编号") String orderNum){
        OrderProductDto orderProductDto = orderProductService.selectOneOrderByOrderNum(orderNum);
        return Result.getResult(OrderProductDto.class).setData(orderProductDto).setMsg("据编号查询单个订单成功");
    }

    /**
     * 用户下单
     * @param form 下单需求
     * @return 返回确定值
     */
    @PostMapping("/createOrderByProduct")
    @ApiOperation("用户下单")
    public Result<Boolean> createOrderByProduct(@RequestBody OrderProductCreateForm form,@RequestHeader @ApiParam("登录用户token") String token){
        String userId = getUserIdByToken(token);
        OrderProductCreateParam param = BeanUtil.toBean(form, OrderProductCreateParam.class);
        param.setUserId(userId);
        param.setOrderTime(LocalDateTime.now().toString());
        //下单
        Boolean aBoolean=orderProductService.createOrderByProduct(param);
        return Result.getResult(Boolean.class).setData(aBoolean).setMsg("下单成功");
    }

    /**
     * 取消订单,待支付时
     * @param form 需要取消订单编号以及理由
     * @param token 登录userID
     * @return 成败信息
     */
    @PostMapping("/cancelOrderByOrderNum")
    @ApiOperation("取消订单,待支付时")
    public Result cancelOrderByOrderNum(@RequestBody OrderProductCancelForm form, @RequestHeader String token){
        String userId = getUserIdByToken(token);

        OrderProductCancelParam param = BeanUtil.toBean(form, OrderProductCancelParam.class);
        param.setUserId(userId);
        orderProductService.cancelOrderByOrderNum(param);
        return Result.getResult().setMsg("订单取消成功");
    }

    /**
     * 修改地址,发货之前
     * @param form 需要取消订单编号以及理由
     * @param token 登录userID
     * @return 成败信息
     */
    @PostMapping("/updateAddressByOrderProduct")
    @ApiOperation("修改地址，发货之前")
    public Result updateAddressByOrderProduct(@RequestBody OrderProductUpdateAddressForm form, @RequestHeader String token){
        String userId = getUserIdByToken(token);

        OrderProductUpdateAddressParam param = BeanUtil.toBean(form, OrderProductUpdateAddressParam.class);
        param.setUserId(userId);

        orderProductService.updateAddressByOrderProduct(param);
        return Result.getResult().setMsg("修改地址成功");
    }

    /**
     * 发起支付订单
     * @param orderProductNum 商品订单编号
     * @param token userId
     * @return 支付表单
     */
    @GetMapping("/pay/{orderProductNum}")
    @ApiOperation("发起支付订单")
    public Result<String> pay(@ApiParam("商品订单编号")@PathVariable("orderProductNum")String orderProductNum,@RequestHeader String token) throws Exception {
        String userId = getUserIdByToken(token);
        String pay=orderProductService.pay(orderProductNum,userId);
        return Result.getResult(String.class).setData(pay).setMsg("发起支付");
    }

    /**
     * 支付回调
     * @param request 请求
     * @return
     * @throws Exception
     */
    @PostMapping("/payNotify")
    @ApiOperation("支付回调")
    public String payNotify(HttpServletRequest request) throws Exception{
        Map<String,String> params = new HashMap<String,String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        System.out.println("params:"+params);
        orderProductService.payNotify(params);
        return "SUCCESS";
    }

    /**
     * 退款(用户)
     * @param orderProductNum 商品订单编号
     * @return boolean判定
     */
    @GetMapping("/refund/{orderProductNum}")
    @ApiOperation("退款(用户)")
    public Result<Boolean> refund(@ApiParam("商品订单编号") @PathVariable("orderProductNum") String orderProductNum,@RequestHeader String token) throws AlipayApiException {
        String userId = getUserIdByToken(token);
        Boolean bool=orderProductService.refund(orderProductNum,userId);
        if(bool){
            return Result.getResult(Boolean.class).setData(bool).setMsg("退款成功");
        }else {
            return Result.getResult(Boolean.class).setData(false).setCode(1000).setMsg("退款失败");
        }

    }

    /**
     * 修改订单评价状态和评分
     * @param form
     * @return
     */
    @PostMapping("/updateReviewStateByOrderProductNum.c")
    @ApiOperation("修改订单评价状态和评分")
    public Result<Boolean> updateReviewStateByOrderProductNum(@RequestBody OrderProductUpdateReviewStateForm form){
        Boolean aBoolean=orderProductService.updateReviewStateByOrderProductNum(form);
        return Result.getResult(Boolean.class).setData(aBoolean).setMsg("修改订单评价状态成功");
    }

    /**
     * 确认完成订单(用户)
     * @param orderProductNum 商品订单编号
     * @param token 用户id
     * @return 布尔值
     */
    @GetMapping("/finishOrder/{orderProductNum}")
    @ApiOperation("确认完成订单,进入售后阶段")
    public Result<Boolean> finishOrder(@ApiParam("商品订单编号") @PathVariable("orderProductNum")String orderProductNum,@RequestHeader String token){
        String userId = getUserIdByToken(token);
        Boolean bool=orderProductService.finishOrder(orderProductNum,userId);
        return Result.getResult(Boolean.class).setMsg("确认订单成功").setData(bool);
    }

    @GetMapping("/upOrder.api")
    @ApiOperation("发货")
    @AdminHistoryLog
    public Result<Boolean> upOrder(@ApiParam("商品订单编号") String orderProductNum){
        Boolean bool=orderProductService.upOrder(orderProductNum);
        return Result.getResult(Boolean.class).setMsg("发货成功").setData(bool);
    }
}

